#pragma once
#include<assert.h>

namespace gugu
{
	template<class T>
	class vector
	{
	public:
		typedef T* iterator;
		typedef const T* const_iterator;

		iterator begin() 
		{
			return _start;
		}

		iterator end() 
		{
			return _finish;
		}

		const_iterator begin() const
		{
			return _start;
		}

		const_iterator end() const
		{
			return _finish;
		}


		vector()
		{
		}

		~vector()
		{
			delete[] _start;
			_start = nullptr;
			_finish = nullptr;
			_endofstorage = nullptr;
		}

		size_t size() const
		{
			return _finish - _start;
		}

		size_t capacity() const
		{
			return _endofstorage - _start;
		}

		 T& operator[](size_t pos) 
		{
			return _start[pos];
		}

		const T& operator[](size_t pos) const
		{
			return _start[pos];
		}

		void reserve(size_t n)
		{
			if (n > capacity())
			{
				T* tmp = new T[n];
				size_t old_size = size();
				memcpy(tmp, _start, sizeof(T) * size());


				delete[] _start;
				_start = tmp;
				_finish = tmp + old_size;
				_endofstorage = tmp + n;
			}
		}

		void resize(const T& n, const T& val = T())
		{
			if (n < size())
			{
				_finish -= n;
			}
			else
			{
				reserve(n);
				for (int i = size(); i < n; i++)
				{
					_start[i] = val;
					_finish++;
				}
			}
		}

		void push_back(const T& val)
		{
			if (_finish == _endofstorage)
			{
				reserve(capacity() == 0 ? 4 : capacity() * 2);
			}

			*_finish = val;
			_finish++;
		}

		bool empty()
		{
			return _start == _finish;
		}

		void insert(iterator pos, const T& val)
		{
			assert(pos <= _finish);
			assert(pos >= _start);

			if (_finish == _endofstorage)
			{
				size_t len = pos - _start;
				reserve( capacity() == 0 ?4 : capacity() * 2);
				pos = _start + len;
			}

			iterator end = _finish - 1;
			while (end >= pos)
			{
				*(end + 1) = *end;
				end--;
			}

			*pos = val;
			_finish++;

		}

		void erase(iterator pos)
		{
			assert(pos <= _endofstorage);

			iterator it = pos+1;
			while (it != end())
			{
				*(it - 1) = *it;
				it++;
			}

			_finish--;
		}
	private:
		T* _start = nullptr;
		T* _finish = nullptr;
		T* _endofstorage = nullptr;
	};

	void test_vertor1()
	{
		vector<int> s1;
		s1.push_back(1);
		s1.push_back(2);
		s1.push_back(3);
		s1.push_back(4);

		for (auto e : s1)
		{
			cout << e << " ";
		}
		cout << endl;

		s1.resize(10, 6);
		for (auto e : s1)
		{
			cout << e << " ";
		}
		cout << endl;

		//vector<int>::iterator 
		//auto pos = std::find(s1.begin(), s1.end());

		s1.insert(s1.begin()+1, 9);
		for (auto e : s1)
		{
			cout << e << " ";
		}
		cout << endl;

		s1.erase(s1.begin() + 1);

		for (auto e : s1)
		{
			cout << e << " ";
		}
		cout << endl;
	}

	void test_vector2()
	{
		vector<string> s1;
		s1.push_back("111111");
		s1.push_back("22222");
		s1.push_back("33333");
		s1.push_back("44444");
		s1.push_back("555555");

		for (auto e : s1)
		{
			cout << e << " ";
		}
		cout << endl;
	}
}
